package com.hewep.demo.device.mina.core;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ActionHandler extends Handler {
	
	private final ActionMapping actionMapping;	
	
	private static final Logger log = LoggerFactory.getLogger(ActionHandler.class);
	
	public ActionHandler(ActionMapping actionMapping) {
		super();
		this.actionMapping = actionMapping;
	}

	public void handle(IoSession session,Request request, Response response) {		
		String method = request.getCmd();
		Action action = actionMapping.getAction(method); 
		if (action == null) {
			log.warn("404 Action Not Found:{}",method);	
			response.setData(new byte[]{0X4F,0X4B});
			session.write(response);
			return ;
		}
		try {
			Controller controller = action.getControllerClass().newInstance();
			log.info("*********************{}",response);
			controller.init(session,request, response);
			
			new ActionInvocation(action, controller).invoke();
			if(response.getData() == null){
				log.info("回复基站内容为空!");
			}else{
				session.write(response);
			}
		}catch(Exception e){
			log.error("Action 【{}】 error:{}",method,e.getMessage());
		}
	}
	
}
